﻿using OestsCommon.Model;
using System;
using System.Collections.Generic;
using System.Data;

namespace OestsDataBase
{
    /// <summary>
    /// 实训操作
    /// </summary>
    public static class TrainDAL
    {
        /// <summary>
        /// 获得所有的数据
        /// </summary>
        /// <returns></returns>
        public static List<TrainData> GetData()
        {
            string strSql = "select * from T_StudentTrainData";
            DataTable dt = SqlHelper.ExecuteDataTable(strSql);
            if (dt == null) { return null; }
            List<TrainData> list = new List<TrainData>();
            foreach (DataRow dr in dt.Rows)
            {
                list.Add(ReadData(dr));
            }
            return list;
        }

        private static TrainData ReadData(DataRow dr)
        {
            TrainData t = new TrainData();
            t.StudentId = Int32.Parse(dr["studentID"].ToString());
            t.ProjectId = Int32.Parse(dr["projectID"].ToString());
            t.TaskId = Int32.Parse(dr["taskID"].ToString());
            t.FinishTime = Int32.Parse(dr["finishTime"].ToString());
            t.HandinTime = Convert.ToDateTime(dr["handinTime"].ToString());
            t.OperationLog = LitJson.JsonMapper.ToObject<List<string>>(dr["operationlog"].ToString());
            t.MemberPosts = dr["memberIds"].Equals(DBNull.Value) ? null : LitJson.JsonMapper.ToObject<List<DP<int, string>>>(dr["memberIds"].ToString());

            return t;
        }

        public static List<TrainData> GetTrainDataByTaskIdOrderByScore(int taskId)
        {
            string strSql = string.Format("select * from T_StudentTrainData where taskID = {0} order by score", taskId);
            DataTable dt = SqlHelper.ExecuteDataTable(strSql);
            if (dt == null) { return null; }
            List<TrainData> list = new List<TrainData>();
            foreach (DataRow dr in dt.Rows)
            {

                list.Add(ReadData(dr));
            }
            return list;
        }

        public static List<TrainData> GetTrainDataByStudentID(int stdId)
        {
            string strSql = string.Format("select * from T_StudentTrainData Where student_id = {0}", stdId);
            DataTable dt = SqlHelper.ExecuteDataTable(strSql);
            if (dt == null) return null;
            List<TrainData> list = new List<TrainData>();
            foreach (DataRow dr in dt.Rows)
            {
                list.Add(ReadData(dr));
            }

            return list;
        }

        public static void AddOccTrain(TrainData data)
        {
            string log = "";
            if (data.OperationLog != null)
            {
                log = LitJson.JsonMapper.ToJson(data.OperationLog);
            }

            //表示没有该学生的该任务该岗位的项目  添加一条
            string strSql2 = string.Format("insert into T_StudentTrainData#Cognitive (studentID,projectID, taskID ,finishTime,handinTime,operationlog) values({0},{1},{2},{3},'{4}','{5}')",
                data.StudentId, data.ProjectId, data.TaskId, data.FinishTime, DateTime.Now.ToString(), log);
            SqlHelper.ExecuteNonQuery(strSql2);
        }

        /// <summary>
        /// 学员提交实训记录
        /// </summary>
        /// <param name="data"></param>
        public static void Add(TrainData data)
        {
            string log = "";
            if (data.OperationLog != null)
            {
                log = LitJson.JsonMapper.ToJson(data.OperationLog);
            }

            string members = "";
            if (data.MemberPosts != null && data.MemberPosts.Count != 0)
            {
                members = LitJson.JsonMapper.ToJson(data.MemberPosts);
            }

            ///#### lym 0926 记录每一次学员的实训记录
            //string strSql1 = string.Format("update T_StudentTrainData set finishTime={0}, operationlog='{1}' where studentID=@student and taskID=@task and projectID=@project",
            //  data.Score, log);
            //int n = SqlHelper.ExecuteNonQuery(strSql1, new SqlParameter("@student", data.StudentId),
            //    new SqlParameter("@task", data.TaskId), new SqlParameter("@project", data.ProjectId));
            //if (n == 0)
            //{
            //表示没有该学生的该任务该岗位的项目  添加一条
            string strSql2 = string.Format("insert into T_StudentTrainData (studentID,projectID, taskID ,finishTime,handinTime,operationlog,memberIds) values({0},{1},{2},{3},'{4}','{5}','{6}')",
                data.StudentId, data.ProjectId, data.TaskId, data.FinishTime, DateTime.Now.ToString(), log, members);
            SqlHelper.ExecuteNonQuery(strSql2);
            // }

        }

        /// <summary>
        /// 删除某个学员ID的所有实训数据
        /// </summary>
        /// <param name="stuId"></param>
        /// <returns></returns>
        public static bool DeleteStudentInfo(int stuId)
        {
            string sql = string.Format("delete from T_StudentTrainData where studentID={0}", stuId);
            int n = SqlHelper.ExecuteNonQuery(sql);
            return true;
        }

        public static bool DeleteStudentInfos(List<int> stuIds)
        {
            string idStr = string.Join(",", stuIds);
            string sql = string.Format("delete from T_StudentTrainData where studentID in ({0})", idStr);
            int n = SqlHelper.ExecuteNonQuery(sql);
            return n > 0;
        }


        #region 实训步骤错误率统计

        public static void UpdateErrorRateStat(int proId, int taskId, int stepIndex, int opIndex, int error)
        {
            string strSql = $"select total,errors from T_StudentTrainDataErrorRateStat where projectId={proId} and taskId={taskId} and stepIndex={stepIndex} and opIndex= {opIndex}";
            DataTable dt = SqlHelper.ExecuteDataTable(strSql);
            if (dt != null && dt.Rows != null && dt.Rows.Count == 1)
            {
                int total = (int)dt.Rows[0]["total"];
                int erorrs = (int)dt.Rows[0]["errors"];
                //更新

                string updateSql = $"update T_StudentTrainDataErrorRateStat set total={total + 1} ,errors={erorrs + error} where projectId={proId} and taskId={taskId} and stepIndex={stepIndex} and opIndex= {opIndex} ";
                SqlHelper.ExecuteNonQuery(updateSql);

            }
            else
            {
                //插入
                string insertSql = $"insert into T_StudentTrainDataErrorRateStat VALUES ({proId}, {taskId},{stepIndex},{opIndex},{1},{error})";
                SqlHelper.ExecuteNonQuery(insertSql);
            }

        }

        /// <summary>
        /// 更新选择题实训的实训次数和错误次数
        /// </summary>
        /// <param name="proId"></param>
        /// <param name="stId"></param>
        /// <param name="subId"></param>
        /// <param name="error"></param>
        public static void UpdateErrorRateStat(int proId, int stId, int subId, int error)
        {
            string strSql = $"select total,errors from T_StudentTrainDataErrorRateStat#Cognitive where projectId={proId} and stId={stId} and subjectid={subId}";
            DataTable dt = SqlHelper.ExecuteDataTable(strSql);
            if (dt != null && dt.Rows != null && dt.Rows.Count == 1)
            {
                int total = (int)dt.Rows[0]["total"];
                int erorrs = (int)dt.Rows[0]["errors"];
                //更新

                string updateSql = $"update T_StudentTrainDataErrorRateStat#Cognitive set total={total + 1} ,errors={erorrs + error} where projectId={proId} and stId={stId} and subjectid={subId}";
                SqlHelper.ExecuteNonQuery(updateSql);

            }
            else
            {
                //插入
                string insertSql = $"insert into T_StudentTrainDataErrorRateStat#Cognitive VALUES ({proId}, {stId},{subId},{error},{1})";
                SqlHelper.ExecuteNonQuery(insertSql);
            }

        }

        public static List<TrainErrorStat> GetErrorRateStat(int proId, int taskId)
        {
            string strSql = $"select stepIndex,opIndex,total,errors from T_StudentTrainDataErrorRateStat where projectId={proId} and taskId={taskId} ";
            DataTable dt = SqlHelper.ExecuteDataTable(strSql);
            if (dt != null && dt.Rows != null)
            {
                List<TrainErrorStat> reList = new List<TrainErrorStat>();
                foreach (DataRow dr in dt.Rows)
                {
                    TrainErrorStat stat = new TrainErrorStat();
                    stat.projectId = proId;
                    stat.taskId = taskId;
                    stat.stepIndex = (int)dr["stepIndex"];
                    stat.opIndex = (int)dr["opIndex"];
                    stat.total = (int)dr["total"];
                    stat.errors = (int)dr["errors"];
                    reList.Add(stat);
                }
                return reList;
            }

            return null;
        }

        #endregion





    }
}
